package com.bailiban.aigou.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.bailiban.aigou.dao.ProductDao;
import com.bailiban.aigou.entity.Product;
import com.bailiban.aigou.utils.PageModel;

@Repository
public class ProductDaoImpl implements ProductDao {
	
	@Autowired
	private SessionFactory sessionFactory;

	@Override
	public void addProduct(Product product) {
		sessionFactory.getCurrentSession().save(product);
	}

	@Override
	public PageModel<Product> getProducts(PageModel<Product> pageModel, Product product) {
		Session session = sessionFactory.getCurrentSession();
		
		Criteria criteria = session.createCriteria(Product.class);
		criteria.setFirstResult((pageModel.getPageNo()-1) * pageModel.getPageSize());
		criteria.setMaxResults(pageModel.getPageSize());
		
		List<Product> list = criteria.list();
		pageModel.setList(list);
		return pageModel;
	}

	@Override
	public void deleteProduct(Product product) {
		sessionFactory.getCurrentSession().delete(product);
	}
}
